import {Component, ViewEncapsulation, ViewChild} from '@angular/core';
import {BaThemeSpinner}  from '../../theme/services';
import {IdeaService} from '../../services/app.idea';
import {UserService} from '../../services/app.user';
import {Utility} from '../../services/app.utility';
import {UserProfile} from '../shared/profile/profile.component';
declare let toastr:any;
declare let $:any;

@Component({
    selector: 'basic-tables',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./leaderboard.scss'],
    templateUrl: './leaderboard.html'
})
export class LeaderBoard {
    @ViewChild(UserProfile)
    profile:UserProfile;
    leaderBoardStats:Array<any>;
    fromDate:string;
    toDate:string;
    myDatePickerOptions:any;
    submitted:boolean;
    public tableValue:boolean;
    public start:any;
    public end:any;
    public check:any;

    constructor(private ideaService:IdeaService, private spinner:BaThemeSpinner, private userService:UserService,
                private utility:Utility) {
        toastr.options = {positionClass: 'toast-top-right'};
        this.submitted = false;
        this.start = 0;
        this.check = 0;

        // Set from and to date to date picker in DD/MM/YYYY format
        this.fromDate = utility.getDatewithoutTimstamp(utility.getXMonthsAgoDate(new Date(), 180));
        this.toDate = utility.getDatewithoutTimstamp(new Date());

        let fromDate:any;
        let toDate:any;

        fromDate = this.fromDate.split("/");

        //from month
        if (fromDate[0] < 10) {
            fromDate[0] = 0 + '' + fromDate[0];
        }

        //from day
        if (fromDate[1] < 10) {
            fromDate[1] = 0 + '' + fromDate[1];
        }

        this.fromDate = fromDate[1] + '/' + fromDate[0] + '/' + fromDate[2];

        //to month
        toDate = this.toDate.split("/");
        if (toDate[0] < 10) {
            toDate[0] = 0 + '' + toDate[0];
        }
        //to day
        if (toDate[1] < 10) {
            toDate[1] = 0 + '' + toDate[1];
        }
        this.toDate = toDate[1] + '/' + toDate[0] + '/' + toDate[2];

        let todayDate = new Date();
        this.myDatePickerOptions = {
            todayBtnTxt: 'Today',
            dateFormat: 'dd/mm/yyyy',
            firstDayOfWeek: 'mo',
            sunHighlight: true,
            height: '34px',
            width: '260px',
            inline: false,
            disableSince: {
                year: todayDate.getFullYear(),
                month: todayDate.getUTCMonth() + 1, day: todayDate.getDate() + 1
            },
            selectionTxtFontSize: '16px'
        };

        // Fuction for call leaderboard function
        this.getleaderBoardStas();

        // function for start timeline count
        this.startCount();
    }

    // Function for change From date of Datepicker
    onFromDateChanged(event:any) {
        if (event.formatted === '') {

        } else {
            let day, month;
            day = event.date.day;
            month = event.date.month;
            if (event.date.month < 10) {
                month = 0 + '' + event.date.month;
            }
            if (event.date.day < 10) {
                day = 0 + '' + event.date.day;
            }

            this.fromDate = day + '/' + month + '/' + event.date.year;
        }
    }

    // Fuction for change To date of datepicker
    onToDateChanged(event:any) {
        if (event.formatted === '') {

        } else {
            let day, month;
            day = event.date.day;
            month = event.date.month;
            if (event.date.month < 10) {
                month = 0 + '' + event.date.month;
            }
            if (event.date.day < 10) {
                day = 0 + '' + event.date.day;
            }
            this.toDate = day + '/' + month + '/' + event.date.year;
        }
    }

    // Fuction for call API for load leaderboard data
    private getleaderBoardStas() {
        this.submitted = true;
        this.spinner.showProgress();
        let input = {
            toDate: this.toDate,
            fromDate: this.fromDate,
        };
        this.ideaService.getLeaderBoardStats(input).subscribe(
            data => this.leaderBoardSucess(data),
            error => this.leaderBoardFailure(error)
        );
    }

    // Fuction call if leaderboard data successfully load
    private leaderBoardSucess(stats) {
        this.submitted = false;
        this.spinner.hideProgress();
        this.leaderBoardStats = stats;
        if (stats.length > 0) {
            this.tableValue = false;
        } else {
            this.tableValue = true;
        }
    }

    // Fuction call if leaderboard data failed to load
    private leaderBoardFailure(error) {
        this.submitted = false;
        this.spinner.hideProgress();
    }

    // Function for view profile and reset previous data
    private viewProfile(id) {
        this.profile.hideEdit();
        this.profile.resetProile();
        this.profile.getUserProfileData(id, undefined, undefined);
    }

    // To call every 1 sec for count how much time we spent on this page
    public  timedCount() {
        this.start = this.start + 1;
        this.end = setTimeout(() => {
            this.timedCount()
        }, 1);
    }

    // To function for start timstamp count
    public startCount() {
        if (!this.check) {
            this.check = 1;
            this.timedCount();
        }
    }

    // To function for stop timstamp count
    public stopCount() {
        clearTimeout(this.end);
        this.check = 0;
    }

    // To call this function when leave from this controller
    ngOnDestroy() {
        // To stop count function call
        this.stopCount();

      // API call for tract navigation sequence
      let seq = {
        sequence: {
          "pageName": 'leaderboard',
          "timeSpent": this.start
        }

      };
      this.userService.setUrlSeq(seq).subscribe();

    }

    // Function call after view for log API
    ngAfterViewChecked() {
        let self = this;
        $('.widgets').unbind().mousedown(function (event) {
            self.checkAllLogs(event);
        });
    }

    // Function for check all logs
    public checkAllLogs(event) {
        let self = this;
        let buttons;
        if (event.button === 0) {
            buttons = 'left click';
        } else if (event.button === 1) {
            buttons = 'roller click';
        } else {
            buttons = 'right click';
        }
        let domTarget = event.target;
        let domTargetString = domTarget.toString();
        let stringDemo = domTargetString.substr(12, 25);
        let index = stringDemo.indexOf('E');
        let dom = stringDemo.substr(0, index);
        let text = $(event.target).unbind().text();


        let input = {
            'target': dom + ' ' + text,
            'value': text,
            'action': buttons
        };

        if (event.target.className === 'btn btn-default btn-auth lgn profileUploadbutton') {
            let data = {
                'target': 'submit',
                'value': 'editProfile',
                'action': 'left click'
            };
            self.userService.setUserLogs(data).subscribe();
        } else {
            self.setUserLogs(input);
        }
    }

    // Function for call API for log
    public setUserLogs(input) {
        this.userService.setUserLogs(input).subscribe();
    }
}
